package org.csu.lestore.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.csu.lestore.api.common.CommonResponse;
import org.csu.lestore.api.entity.Account;
import org.csu.lestore.api.entity.Category;
import org.csu.lestore.api.entity.Img;
import org.csu.lestore.api.entity.Item;
import org.csu.lestore.api.persistence.*;
import org.csu.lestore.api.service.ImgService;
import org.csu.lestore.api.vo.CategoryVO;
import org.csu.lestore.api.vo.ItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("imgService")
public class ImgServiceImpl implements ImgService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private ImgMapper imgMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ItemMapper itemMapper;

    @Override
    public CommonResponse<Img> deleteImg(Img img) {
        if(img.getImgId()==-1){
            return CommonResponse.createForError("不能删除默认图片");
        }
        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("img_id",img.getImgId());
        List<Account> accountList = accountMapper.selectList(accountQueryWrapper);
        if(accountList!=null){
            for(Account account : accountList){
                account.setImgId(-1);
                accountMapper.update(account,accountQueryWrapper);
            }
        }
        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("img_id",img.getImgId());
        List<Item> itemList = itemMapper.selectList(itemQueryWrapper);
        if(itemList!=null){
            for(Item item : itemList){
                item.setItemImg(-1);
                itemMapper.update(item,itemQueryWrapper);
            }
        }
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.eq("img_id",img.getImgId());
        List<Category> categoryList = categoryMapper.selectList(categoryQueryWrapper);
        if(categoryList!=null){
            for(Category category : categoryList){
                category.setCategoryImg(-1);
                categoryMapper.update(category,categoryQueryWrapper);
            }
        }

        QueryWrapper<Img> imgQueryWrapper = new QueryWrapper<>();
        imgQueryWrapper.eq("img_id",img.getImgId());
        imgMapper.delete(imgQueryWrapper);
        return CommonResponse.createForSuccessMessage("删除成功");
    }

    @Override
    public CommonResponse<IPage<Img>> getImgList(int curPage, int size) {
        IPage<Img> page = new Page<>(curPage,size);
        imgMapper.selectPage(page,null);

        return CommonResponse.createForSuccess(page);
    }
}
